#!/usr/bin/perl -w

BEGIN   
{
	sub getPoints{return '../../' if (!$_[1]);return '../' if (!$_[0]);return '/';}
	(my $file = __FILE__) =~ s/\/?(modules\/)?(con_track\/)?(\w+\.pl)$/&getPoints($1,$2)/e;
	$file = './' if $file eq '/';
	unshift(@INC, $file."bin");
}

use strict;
use TWM;
use Data::Dumper;

my $host = $ARGV[0];
my $boundary = '____sdgjskdgnwurtigsdmbnsoruitwegnsdmfgbnsdugwiegmasdngfdhwrutgbrbmslgnaigqjlkr;tjergiorbnjwuegqkrjgdbnsdm,bnsug';
my @ip;

if ($host)
{
	push @ip, {'ip'=>$host, 'name'=>''};
}
else
{
	my $isp = &getISP;
	foreach my $inf (keys %$isp)
	{
		push @ip, {'ip'=>$isp->{$inf}->{ip}, 'name'=>$isp->{$inf}->{code}};
	}
}

print <<__EOF;
fullrow=0
boundary=$boundary
__EOF

for my $host (@ip)
{
	print <<__EOF;

$boundary
<div class="paneltitle"><span class="paneltitlerow">Connections $host->{name}</span></div>
<div class="panelcontent">
<div class="panelcontentrow">

<table cellspacing=0 cellpadding=0 width=100% border=0>
  <tr bgcolor=#dddddd>
    <td width=100%>
<table cellpadding=1 cellspacing=1 border=0 width=100%>
  <tr>
    <th width=50>Proto</th>
    <th>Source</th>
    <th>Destination</th>
    <th width=50>Masq</th>
  </tr>
__EOF
	my $cl = "$cm{ip_conntrack} -tw --host $host->{ip}";
	my @ip_conntrack = run_twm_script($cl, $mc);

	my (%ip_track);
	foreach (@ip_conntrack)	
	{
		next if !$_;
		my ($proto, $ip_src, $port_src, $ip_dst, $port_dst, $port, $state, $masq, $dirrection) = ($1, $2, $3, $4, $5, $6, $7, $8, $9) if (/^(\w+)\t(\S+)\:(\d+)\t(\S+)\:(\d+)\t(.+)\t(.+)\t(.+)\t(.+)\t/);
		if ($proto)
		{
			if ($ip_src eq $host->{ip} || $ip_dst eq $host->{ip})
			{
				print <<__EOF;
  <tr bgcolor=#ffffff onmouseover="ovrMouse(this);" onmouseout="outMouse(this);">
    <td width=50>&nbsp;$proto</td>
    <td>&nbsp;<a class=grid href="/cgi-bin/modules/con_track/who.pl?host=$ip_src" target=_blank>$ip_src</a>:$port_src</td>
    <td>&nbsp;<a class=grid href="/cgi-bin/modules/con_track/who.pl?host=$ip_dst" target=_blank>$ip_dst</a>:$port_dst</td>
    <td width=50>&nbsp;$masq</td>
  </tr>
__EOF
			}
		}
		else	
		{
			toErrorLog("Can not parse: $_");
		}
	}

	print <<__EOF;
</table>
    </td>
  </tr>
</table>
</div>
</div>
__EOF
}


